<template>
  <div class="editAgent">
    <el-form ref="editAgentRefs" v-loading="editAgentLoading" :model="editAgentForm" :rules="editAgentRules" label-width="100px" class="editAgentCls">
      <el-form-item label="用户：" prop="headImage">
        <div class="upLoadPicBox">
          <div v-if="editAgentForm.headImage" class="pictrue">
            <el-image ref="initialLargePreView" class="imgHover" :src="$uploadURL(editAgentForm.headImage)" :preview-src-list="[$uploadURL(editAgentForm.headImage)]" />
            <div class="upload_cover_preview">
              <i class="iconfont icon-yanjing" @click.stop="largePreview('initialLargePreView')" />
              <i class="el-icon l-upload el-icon-delete" @click.stop="delLarge(1)" />
            </div>
          </div>
          <div v-else class="upLoad" @click="tabChange"><i class="el-icon l-upload el-icon-camera-solid" /></div>
        </div>
      </el-form-item>
      <el-form-item label="角色：" class="selectFormWidth100" prop="agentRoleId">
        <el-select v-model="editAgentForm.agentRoleId" placeholder="请选择角色" size="small" clearable @change="change">
          <el-option v-for="item in tableAgentRolesList" :key="item.id" :label="`${ item.name }（${ item.levelName }）`" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="上级代理：" class="selectFormWidth100">
        <el-select v-model="editAgentForm.refAgentId" placeholder="请选择上级代理" size="small" clearable @visible-change="visibleChange">
          <el-option label="请选择上级代理" :value="-99" />
          <el-option v-for="(item, index) in refAgentList" :key="index" :label="`${ item.name }（${ item.agentRole.name }（${ item.agentRole.levelName }））`" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="名称：" prop="name">
        <el-input v-model="editAgentForm.name" placeholder="请输入代理名称" size="small" clearable />
      </el-form-item>
      <el-form-item label="手机号：" prop="mobile">
        <el-input v-model="editAgentForm.mobile" placeholder="请输入手机号" size="small" clearable />
      </el-form-item>
      <el-form-item label="提成：" prop="commission">
        <el-input v-model="editAgentForm.commission" placeholder="请输入提成" size="small" clearable>
          <i slot="suffix" style="font-style:12px;margin-right: 5px;">%</i>
        </el-input>
      </el-form-item>
      <el-form-item v-if="isEdit == 1" label="创建时间：">
        <el-input v-model="editAgentForm.createDateUTC" disabled placeholder="创建时间" size="small" clearable />
      </el-form-item>
      <div class="subBtnWid">
        <el-button size="small" type="primary" :loading="loadingBtn" @click="subAgent('editAgentRefs')">提交</el-button>
      </div>
      <div class="subBtnWid">
        <el-button size="small" @click="subClone('editAgentRefs')">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import {
  getAppointAgentInfoApi,
  getRolesListApi,
  PUTEditAgentApi as putEditAgentApi,
  getRefAgentApi,
  POSTAddAgentApi as postAddAgentApi
} from '@/api/agent'

export default {
  name: 'Index',
  props: {
    editId: {
      type: [String, Number],
      default: 0
    },
    isEdit: {
      type: [String, Number],
      default: 0
    }
  },
  data() {
    const validateMobile = (rule, value, callback) => {
      if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    const validatorMoney = (rule, value, callback) => {
      if (!/(^[1-9]([0-9]+)?(.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9].[0-9]([0-9])?$)/.test(value) && value) {
        callback(new Error('请输入正整数或小数保留两位小数'))
      } else {
        callback()
      }
    }
    return {
      editAgentForm: {
        userId: '',
        headImage: '',
        refAgentId: -99,
        agentRoleId: '',
        name: '',
        mobile: '',
        commission: '',
        createDateUTC: ''
      },
      refAgentId: 0,
      editAgentRules: {
        headImage: [
          { required: true, message: '请选择商品', trigger: 'change' }
        ],
        agentRoleId: [
          { required: true, message: '请选择代理角色', trigger: 'change' }
        ],
        name: [
          { required: true, message: '代理名称不能为空', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'change' },
          { validator: validateMobile, trigger: 'blur' }
        ],
        commission: [
          { required: true, message: '提成不能为空', trigger: 'change' },
          { validator: validatorMoney, trigger: 'change' }
        ]
      },
      tableAgentRolesList: [],
      refAgentList: [],
      editAgentLoading: false,
      loadingBtn: false,
      level: 0,
      oldLevel: 0
    }
  },
  mounted() {
    if (this.isEdit != 0) this.getAppointAgentInfo()
    this.getAgentRoles()
  },
  methods: {
    /**
       * 选择用户类型
       */
    tabChange() {
      const _this = this
      _this.$modal({
        componentProps: {},
        component: (resolve) => require(['@/components/userTable'], resolve),
        props: {
          title: '选择用户',
          customClass: 'zdyDialogCls agentUserDialogCls',
          width: '100%',
          closeOnClickModal: false
        },
        methods: {
          retUserTab(row) {
            _this.$set(_this.editAgentForm, 'headImage', row.headImage)
            _this.$set(_this.editAgentForm, 'userId', row.id)
            _this.$refs.editAgentRefs.validateField('headImage')
          }
        }
      })
    },
    /**
       * 角色信息改变时
       */
    change() {
      const roles = this.tableAgentRolesList.find((item) => item.id == this.editAgentForm.agentRoleId)
      this.$set(this, 'level', roles.level)
      this.getRefAgents(this.level)
    },
    /**
       * 下拉框打开时
       */
    visibleChange(vis) {
      // eslint-disable-next-line eqeqeq
      if (vis && this.isEdit != 1) {
        // eslint-disable-next-line eqeqeq
        if (this.level == this.editAgentForm.agentRoleId) return
        this.getRefAgents(this.level)
      }
    },
    /**
       * 关闭
       */
    subClone() {
      this.$emit('close')
    },
    /**
       * 提交
       */
    subAgent(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // eslint-disable-next-line eqeqeq
          if (this.isEdit == 1) {
            this.$set(this, 'loadingBtn', true)
            putEditAgentApi(this.editId, {
              userId: this.editAgentForm.userId,
              // eslint-disable-next-line eqeqeq
              refAgentId: this.editAgentForm.refAgentId == -99 ? 0 : this.editAgentForm.refAgentId,
              agentRoleId: this.editAgentForm.agentRoleId,
              name: this.editAgentForm.name,
              mobile: this.editAgentForm.mobile,
              commission: this.editAgentForm.commission
            }).then(() => {
              this.$message.success('编辑成功')
              this.$emit('getAgentList')
              this.$emit('close')
              this.$set(this, 'loadingBtn', false)
            }).catch(() => {
              this.$set(this, 'loadingBtn', false)
            })
          } else {
            this.$set(this, 'loadingBtn', true)
            postAddAgentApi({
              userId: this.editAgentForm.userId,
              // eslint-disable-next-line eqeqeq
              refAgentId: this.editAgentForm.refAgentId == -99 ? 0 : this.editAgentForm.refAgentId,
              agentRoleId: this.editAgentForm.agentRoleId,
              name: this.editAgentForm.name,
              mobile: this.editAgentForm.mobile,
              commission: this.editAgentForm.commission
            }).then(() => {
              this.$message.success('添加成功')
              this.$emit('getAgentList')
              this.$emit('close')
              this.$set(this, 'loadingBtn', false)
            }).catch(() => {
              this.$set(this, 'loadingBtn', false)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    /**
       * 删除图片
       */
    delLarge() {
      this.$set(this.editAgentForm, 'userId', 0)
      this.$set(this.editAgentForm, 'headImage', '')
    },
    /**
       * 大图预览
       */
    largePreview(ref) {
      this.$refs[ref].clickHandler()
    },
    /**
       * 获取代理商角色信息
       */
    getAgentRoles() {
      getRolesListApi({
        pageNumber: 1,
        pageSize: 30
      }).then(res => {
        this.$set(this, 'tableAgentRolesList', res.data)
      })
    },
    /**
       * 获取上级代理
       */
    getRefAgents(level) {
      // eslint-disable-next-line eqeqeq
      if (level == this.oldLevel) return
      this.oldLevel = level
      this.$set(this, 'editAgentLoading', true)
      getRefAgentApi(level, {
        pageNumber: 1,
        pageSize: 30,
        orderBy: 'Id desc'
      }).then(res => {
        // eslint-disable-next-line eqeqeq
        if (this.isEdit == 1 && res.data.find((item) => item.id == this.refAgentId)) this.$set(this.editAgentForm, 'refAgentId', this.refAgentId)
        else if (!res.data.find((item) => item.id == this.editAgentForm.refAgentId)) this.$set(this.editAgentForm, 'refAgentId', -99)
        this.$set(this, 'refAgentList', res.data)
        this.$set(this, 'editAgentLoading', false)
      }).catch(() => {
        this.$set(this.editAgentForm, 'refAgentId', -99)
        this.$set(this, 'refAgentList', [])
        this.$set(this, 'editAgentLoading', false)
      })
    },
    /**
       * 获取指定代理信息
       */
    getAppointAgentInfo() {
      this.$set(this, 'editAgentLoading', true)
      getAppointAgentInfoApi(this.editId).then(res => {
        this.$set(this, 'level', res.agentRole.level)
        this.$set(this, 'refAgentId', res.refAgentId)
        this.getRefAgents(res.agentRole.level)
        this.$set(this, 'editAgentForm', {
          userId: res.user.id,
          headImage: res.user.headImage,
          agentRoleId: res.agentRoleId,
          refAgentId: res.refAgentId,
          name: res.name,
          mobile: res.mobile,
          commission: res.commission,
          createDateUTC: this.$util.uctTimeFileter(res.createDateUTC)
        })
        this.$set(this, 'editAgentLoading', false)
      }).catch(() => {
        this.$set(this, 'editAgentForm', {})
        this.$set(this, 'editAgentLoading', false)
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>

<style lang="scss">
  .el-dialog.agentUserDialogCls {
    max-width: 1000px;
  }
</style>
